package com.zhiwang.planet.util

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Build
import android.telephony.SubscriptionManager
import android.telephony.TelephonyManager
import android.text.TextUtils
import androidx.appcompat.app.AppCompatActivity
import com.zhiwang.planet.App
import com.zhiwang.planet.event.LoginEvent
import com.zhiwang.planet.mvvm.model.entity.User
import com.zhiwang.planet.ui.loginv2.WxLoginActivity
import org.greenrobot.eventbus.EventBus

object AppUtil : MiitHelper.AppIdsUpdater {


    fun handleLogin(token: String) {
        TokenManager.saveToken(token)
        EventBus.getDefault().post(LoginEvent())
        TokenManager.setPhoneLogged()
    }

    fun handleUserLogin(it: User) {
//        if (AppDataBase.getInstance(App.instance).userDao().getUsersSync().isEmpty()) {
//            TokenManager.saveUserid(it.userId)
//            TokenManager.savePhone(it.phone)
//            //每次登陆切换，都设置异常上报的 userid
//            YmConfig.setOutUserId(it.userId)
//            CrashReport.setUserId(TokenManager.webviewHeaderUserid())
//        }else{
//            TokenManager.saveUserid(it.userId)
//        }
    }

    fun handleLogout(context: AppCompatActivity) {
        TokenManager.clearToken()
//        AppDataBase.getInstance(context).userDao().deleteAll()

//        if (TokenManager.hasPhoneLogged())
        context.quickStartActivity(WxLoginActivity::class.java)
//        else context.quickStartActivity(LoginV2Activity::class.java)
    }

    fun onAuthExpired(context: Context) {
//        if (TokenManager.hasPhoneLogged())
        context.startActivity(Intent(context, WxLoginActivity::class.java))
//        else context.startActivity(Intent(context, LoginV2Activity::class.java))
    }


    /*获取设备码*/

    var deviceId: String = ""

    var onFetch: ((String) -> Unit)? = null

    @SuppressLint("MissingPermission", "HardwareIds")
    fun getDeviceId(onFetch: (String) -> Unit) {
        this.onFetch = onFetch
        deviceId = "无法获取设备号"
        val telephonyManager = App.instance.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        deviceId = when {
            Build.VERSION.SDK_INT > Build.VERSION_CODES.P -> {
                // oaid for android 10
                retrieveOAIDForAndroidQ()
                ""
            }
            //old deviceid
            TextUtils.isEmpty(telephonyManager.deviceId).not() -> {
                telephonyManager.deviceId
            }

            // imei
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> retrieveImeiExcludeMeid(telephonyManager)

            //failed
            else -> ""
        }

        if (TextUtils.isEmpty(deviceId).not())
            onFetch.invoke(deviceId)


    }

    /**
     *获取设备码，优先过滤掉 meid
     *如果 imei0 和 meid 相同，先排除 imei0 ,获取 imei1 ,否则取 imei0
     */
    @SuppressLint("NewApi", "MissingPermission")
    private fun retrieveImeiExcludeMeid(telephonyManager: TelephonyManager): String {

        val meid0 = telephonyManager.getMeid(0) ?: ""
        val meid1 = telephonyManager.getMeid(1) ?: ""


        val meid = if (TextUtils.isEmpty(meid0)) meid1 else meid0


        val imei0 = telephonyManager.getImei(0) ?: ""
        val imei1 = telephonyManager.getImei(1) ?: ""


        val imei = when {
            TextUtils.isEmpty(meid) -> imei0
            TextUtils.equals(meid, imei0) -> imei1
            else -> imei0
        }
        return imei
    }

    private fun retrieveOAIDForAndroidQ() {
        if (TokenManager.oaid().isNotEmpty())
            onFetch?.invoke(TokenManager.oaid())
        else MiitHelper(this).getDeviceIds(App.instance)
    }


    override fun OnIdsAvalid(ids: String) {
        TokenManager.saveAndroid10Oaid(ids)
        onFetch?.invoke(ids)
    }

    override fun OnIdsError(msg: String?) {
        msg?.apply { Toaster.message(this) }
    }


    @SuppressLint("MissingPermission")
    fun checkSimInsert(): Boolean {
        return checkByTelephony() || checkBySub()
    }


    private fun checkByTelephony(): Boolean {
        val telMgr = App.instance.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        val simState = telMgr.simState
        var result = true
        when (simState) {
            TelephonyManager.SIM_STATE_ABSENT -> result = false
            TelephonyManager.SIM_STATE_UNKNOWN -> result = false
        }

        return result
    }

    @SuppressLint("MissingPermission")
    private fun checkBySub(): Boolean {

        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
                val subscriptionManager = App.instance.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE) as SubscriptionManager
                return subscriptionManager.activeSubscriptionInfoList != null
                        && subscriptionManager.activeSubscriptionInfoList.isNotEmpty()
            }
        } catch (e: Exception) {

        }

        return true
    }

}